package org.test.client.ui.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;

public class Icons {
	
	public static GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
	public static GraphicsConfiguration deCfg = environment.getDefaultScreenDevice().getDefaultConfiguration();
	
	public static String dynamicFontPath = "font/fontawesome-webfont.ttf";
	public static Font iconFont = null;
	
	static{
		try {
			iconFont = Font.createFont(Font.TRUETYPE_FONT, new File(dynamicFontPath));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Color getColor(String hexStr){
		return new  Color(Integer.parseInt(hexStr,16));
	}
	
	public static Icon getIconByDesc(String desc, int w, Color color) {
		String string = FontAwesome.faMap.get(desc);
		
		return new ImageIcon(getImgByFontHex(string ,w, color));
	}
	
	public static BufferedImage getImgByDesc(String desc, int w, Color color) {
		String string = FontAwesome.faMap.get(desc);
		
		return getImgByFontHex(string ,w, color);
	}
	
	public static BufferedImage getImgByFontHex(String iconHex, int w, Color color) {

//		BufferedImage img = new BufferedImage(w, w, Transparency.TRANSLUCENT);
		BufferedImage img = deCfg.createCompatibleImage(w, w, Transparency.TRANSLUCENT);
		Graphics2D g = img.createGraphics();

		//此处 必须为 float 若为 int 则 调用 deriveFont(int style)
		float neww = w-2;
		Font tmpFont = iconFont.deriveFont(neww);
		g.setFont(tmpFont);
		
		if(color != null){
			g.setColor(color);
		}else{
			g.setColor(new Color(0xff000000, true));
		}

		FontMetrics fm = g.getFontMetrics();
		int stringWidth = fm.stringWidth(iconHex);
		int stringAscent = fm.getAscent();
		int stringDescent = fm.getDescent();
		int x = w / 2 - stringWidth / 2;
		int y = w / 2 + (stringAscent - stringDescent) / 2;
		UIUtil.setAntiAliasing(g, true);
		g.drawString(iconHex, x, y);

//		try {
//			ImageIO.write(img, "png", new File("C:/test.png"));
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		
		return img;

	}
	
	
	public static  Icon loadIcon(String path){
		BufferedImage bi =  loadImg(path);
		Icon icon = new ImageIcon(bi);
		return icon;
	}
	
	public static BufferedImage loadImg(String path){
		BufferedImage bi = null;
		try {
			bi = ImageIO.read(new File(path));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bi;
	}
	
	public static void main(String[] args) {
		Integer in = new Integer(61485);
		System.out.println(in.toHexString(61485));
		
		Integer in2 = Integer.parseInt("F02c", 16);
		System.out.println(in2);
		
	}
}
